package com.ldpp.disruptor.engine;

import com.ldpp.disruptor.event.Event;
import com.ldpp.disruptor.factory.LdppEventFactory;
import com.ldpp.disruptor.handler.LdppEventhandler;
import com.ldpp.disruptor.producer.LdppEventProducer;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ：gongtan
 * @date ：Created in 2021/3/15 10:21
 * @description：
 * @modified By：
 */
public class engineMain {

    //事件引擎开关标识
    private static boolean active = false;

    //生产者对象
    private static LdppEventProducer ldppEventProducer;

    public  static void  start (){
        //1.创建可以缓存的线程池 ，提供发给消费者
        ExecutorService executor = Executors.newCachedThreadPool();
        //2.创建 event工厂
        LdppEventFactory ldppEventFactory = new LdppEventFactory();
        //3.创建ringbuffer 大小   2的N次方
        int ringbuff=1024*1024;
        //4.创建disruptor
        Disruptor<Event> disruptor = new Disruptor<>(ldppEventFactory, ringbuff, executor, ProducerType.MULTI, new YieldingWaitStrategy());
        //5.连接消费者 —————— 注册消费者 标识把生产者数据 推送出去
        disruptor.handleEventsWith(new LdppEventhandler());
        //6.启动
        disruptor.start();
        //标注事件引擎为 启动状态
        System.out.println("事件引擎启动");
        active = true;
        //7.创建ringbuff容器
        RingBuffer<Event> ringBuffer = disruptor.getRingBuffer();
       //8.创建生产者  此单一生产者 生产不同类型的数据
        ldppEventProducer = new LdppEventProducer(ringBuffer);

        /* disruptor 线程关闭
        executor.shutdown();
        disruptor.shutdown();*/
    }

    //生产数据 调用方法
    public static void creatEvent(Event event){
        if(!active){
            start();
        }else{
            ldppEventProducer.onData(event);
        }
    }
}
